class StoreController < ApplicationController
 before_filter :login_required, :only => [ :checkout, :add_line_items ]
  verify :method => :post, :only => [:add_product_to_cart, :add_meal_to_cart, :empty_cart], :redirect_to => {:action => :index }
  
  def index
    @products = Product.find(:all)
    @meals = Meal.find(:all)
  end
  
  def add_product_to_cart
    begin
      product = Product.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      logger.error("Attempt to access invalid product #{params[:id]}")
      flash[:notice] = "There's no such product"
    else
      @cart.add_product(product)
    end
    redirect_to :action => :index
  end
  
  def remove_product_from_cart
    begin
      product = Product.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      logger.error("Attempt to access invalid product #{params[:id]}")
      flash[:notice] = "There's no such product"
    else
      @cart.remove_product(product)
    end
    redirect_to :action => :index
  end
  
  def add_meal_to_cart
    begin
      meal = Meal.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      logger.error("Attempt to access invalid meal #{params[:id]}" )
      flash[:notice] = "There's no such meal"
    else
      @cart.add_meal(meal)
    end
    redirect_to :action => :index
  end
  
  def remove_meal_from_cart
    begin
      meal = Meal.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      logger.error("Attempt to access invalid meal #{params[:id]}" )
      flash[:notice] = "There's no such meal"
    else
      @cart.remove_meal(meal)
    end
    redirect_to :action => :index
  end
  
  def empty_cart
    session[:cart_data] = nil
    redirect_to :action => :index
  end
  
  def checkout
    if(current_user.user_groups.count == 1)
      @selected_group = current_user.user_groups[0].id
    end
  end
  
  def add_line_items
    product_items = @cart.product_items
    meal_items = @cart.meal_items

    product_items.each do |product_item|
      ProductLineItem.create(:product_id => product_item.item.id, 
                             :name => product_item.item.name,
                             :quantity => product_item.quantity, 
                             :total_price => product_item.price, 
                             :user_id => current_user.id,
                             :user_group_id => nil)
    end
    
    meal_items.each do |meal_item|
      MealLineItem.create(:meal_id => meal_item.item.id, 
                          :name => meal_item.item.name,
                          :quantity => meal_item.quantity, 
                          :total_price => meal_item.price, 
                          :user_id => current_user.id,
                          :user_group_id => nil)
    end

    session[:cart_data] = nil
    flash[:notice] = "Thank you for your order"
    redirect_to(line_items_path)
  end
end
